package com.dkx.wm.controller;
import com.alibaba.fastjson.JSON;
import com.dkx.wm.entity.Result;
import com.dkx.wm.entity.User;
import com.dkx.wm.mapper.UserMapper;
import com.dkx.wm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@Controller
@CrossOrigin
@RequestMapping("/users")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;



    /**
     * 查询所有的用户信息
     * @return
     */
    @GetMapping
    public Result<User> list(){
        List<User> userList = userMapper.selectAll();
        String jsonString = JSON.toJSONString(userList);
        return new Result<>().setData(jsonString).setCode(200);
    }

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User getbyUserId(@PathVariable int id){
            return userService.getUserById(id);
    }

    /**
     * 增加用户操作
     */
    @PostMapping
    public Result addUser(@RequestBody User user){
        userService.addUser(user);
        return new Result().setMsg("成功添加").setCode(200);
    }

    @DeleteMapping("/{id}")
    public Result delectUserById(@PathVariable("id") Integer id){
        userService.deleteUser(id);
        return new Result().setCode(200).setMsg("成功删除");
    }

    /**
     * 修改用户的操作
     * @param user
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public Result updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
            // 可选：设置 ID 到 user 对象中，确保 ID 一致
//        System.out.println(user + "id" +id);
        //1.判断用户是否存在
        User us = userMapper.selectById(id);
        //2.修改用户
        if (us!=null){
            userMapper.update(user);
        }
        return new Result().setCode(200).setMsg("成功修改");
    }

    /**
     * 分页插件
     * pageNow当前页
     * pageSize最大页
     */
    @GetMapping("/page")
    public Result<List<User>> getUsetList(@RequestParam(value = "pageNow",defaultValue = "1") int pageNow,
                                            @RequestParam(value = "pageSize",defaultValue = "3") int pageSize){
        List<User> userList = userService.getUserInfoList(pageNow,pageSize);
        return new Result<>().setData(userService.getUserInfoList(pageNow,pageSize));
    }

}